$(function(){	
	//显示未对照结果选择框值变动监听
	$("#"+tabId+" #showUnvalidResult").on('ifChanged',function(){
		if(this.checked){
			loadTableData(1);
		}else{
			loadTableData(0);
		}
	})
	initIcdVersion($("#"+tabId+" #icdTypeId").val(),'icdVersion');
	loadTableData(0);
	//编码类型下拉框值变动监听
	$("#"+tabId+" #icdTypeId").on("change",function(){
		initIcdVersion($(this).val(),'icdVersion',true);
	})
	//版本号下拉框值变动监听
	$("#"+tabId+" #icdVersion").on("change",function(){
		if($("#"+tabId+" #showUnvalidResult").checked){
			loadTableData(1);
		}else{
			loadTableData(0);
		}
	})
		//单条录入
	$("#"+tabId+" #updateDiagButton").click(function(){
		ICDDiagDialog();
	})
	
	//文件上传
	$("#"+tabId+" #import_icdDiag_file").uploadifive({
		'uploadScript' : contextPath + '/matchIcd/fileUploadICD.dhc',
        'height': 31 ,
        'width' :120 ,
        'auto'  : true ,//是否自动开始
        'uploadLimit' : 100, //一次同步上传的文件数目     
        'fileSizeLimit' : '500MB', //单个文件大小，0为无限制，可接受KB,MB,GB等单位的字符串值     
        'queueSizeLimit' : 100, //队列中同时存在的文件个数限制
        'fileObjName':'file',
        'removeCompleted': true , //是否完成后移除序列，默认为true
        'removeTimeout' : '5',  //上传完成后队列多长时间后消失。默认 3秒    需要：removeCompleted : true,时使用
        'progressData' :'percentage',//设置上传进度显示方式，percentage显示上传百分比，speed显示上传速度
        'buttonText' : '<i class="fa fa-folder-open fa-lg"></i>&nbsp;&nbsp;选择导入文件',
        'buttonClass': 'uploadifyH5_blue_btn',
        'fileType' : '*.xls; *.xlsx; *.xml; *.dbf',//允许上传的文件格式
        'multi'    : true,//是否支持多文件上传
        'method'   :'post',//提交方式
        'debug':false,
        //当点击文件队列中文件的关闭按钮或点击取消上传时触发
        'onCancel': function(){ },
      	//返回一个错误，选择文件的时候触发  
        'onSelectError':  function(){
        	drgUI.error("文件上传失败！") ;
        },
      	//检测FLASH失败调用  
        'onFallback':function(){  
            drgUI.error("浏览器检测不到兼容版本的HTML5。 ") ;
        }, 
        'onUploadError' : uploadify_onUploadError,
        'onQueueComplete':function(res){
        	 ICDMATCH.showProgress("dia");//获取进度
			   $.ajax({
		       		 url :contextPath+'/matchIcd/analysisICDPlatform.dhc',
		       		 data : {
		       			 "icdVersion": $("#"+tabId+" #icdVersion").val(),
		       			 "icdType":$("#"+tabId+" #icdTypeId").val()
		       		 },
		       		 type:'post',
		       		 async:true,
		       		 dataType : "json",//这里的dataType就是返回回来的数据格式了html,xml,json
		       		 cache: false,//设置是否缓存，默认设置成为true，当需要每次刷新都需要执行数据库操作的话，需要设置成为false
		       		 success : function(result) {	 
		       			if(!result.success){
		       				drgUI.warning("请检测数据文件准确性");
		       				alert(1)
		       				return;
			       		}else{
			       			drgUI.success("导入成功！");
			       			if($("#"+tabId+" #showUnvalidResult").checked){
			       				loadTableData(1);
			       			}else{
			       				loadTableData(0);
			       			}
			       		}
		       		 }
		       	 });
		}
	}); 
	
	//加载版本下拉框
	function initIcdVersion(icdType,selectId,sync){
		var dicCode = 'DIA_ICD_VERSION';
		if( dicCode && dicCode == 'O'){
			dicCode = 'OPER_ICD_VERSION';
		}
		$.post(contextPath + "/dictionaryData/getDictionaryDataByCode.dhc", {dicCode:dicCode}).done(function(result){
			if(result.data){
				$("#"+tabId+" #"+selectId).html('');
				var versions = result.data, str ='';
				for(var i in versions){
					str += '<option value="'+versions[i].DICVALUE+'">'+versions[i].DICDESC+'</option>';
				}
				$("#"+tabId+" #"+selectId).html(str);
				if(sync){
					if($("#showUnvalidResult").checked){
						loadTableData(1);
					}else{
						loadTableData(0);
					}					
				}
			}
		});
	}
	
	/*
	 * 单条录入的弹出框
	 */
	function ICDDiagDialog(){
		var ckd = $("#"+tabId+" #showUnvalidResult").checked;
		$.post(contextPath + '/pages/icdMatch/top-dialog.jsp').done(function(dialogdata){
			var dialog = $(dialogdata);
			var icdType=$("#"+tabId+" #icdTypeId").val();
			dialog.find(".modal-title").html( icdType == "D" ? " 增加或更新ICD诊断对照 ":" 增加或更新ICD手术对照 ");//顶部标题
			dialog.find(".modal-dialog").css("width","40%");//弹出框宽度	
			dialog.find(".modal-body").css("min-height","260px");//高度	
			dialog.modal({
							keyboard : false
						}).on({
								'hidden.bs.modal': function(){
									$(this).remove();
								},
								'shown.bs.modal' : function(){
									var diagCodeLabel,diagCodeInput,diagDescLabel,diagDescInput,bjCodeLabel,bjCodeInput,bjCodeDescLabel,bjCodeDescInput;
									if(icdType == "D"){
										diagCodeLabel = '医院ICD诊断编码:';
										diagCodeInput = '请输入本院诊断编码';
										diagDescLabel = '医院ICD诊断描述:';
										diagDescInput = '医院ICD诊断描述为：描述(病例数)';
										bjCodeLabel = '北京ICD诊断编码:';
										bjCodeInput = '请输入北京诊断编码';
										bjCodeDescLabel = '北京ICD诊断描述:';
										bjCodeDescInput = '';
									}else{
										diagCodeLabel = '医院手术ICD编码:';
										diagCodeInput = '请输入本院手术编码';
										diagDescLabel = '医院手术ICD描述:';
										diagDescInput = '';
										bjCodeLabel = '北京手术ICD编码:';
										bjCodeInput = '请输入北京手术编码';
										bjCodeDescLabel = '北京手术ICD描述:';
										bjCodeDescInput = '';										
									}
									dialog.find(".modal-body").empty();
									var str = '';
									str+='<div class="container-fluid">';
									str+='<div class="row" style="height:30px;margin-top:20px;">';
									str+='<div class="col-xs-4"  >';
									str+='<label class="control-label" style="text-align:right;float:right;line-height:30px;width:100%">'+diagCodeLabel+'</label>';
									str+='</div>';
									str+='<div class="col-xs-6"">';
									str+='<input id="hICDCode" type="text" class="form-control" placeholder="'+diagCodeInput+'" onblur="findDiagOrOperateDescByCode(\''+icdType+'\')">';
									str+='</div>';
									str+='</div>';
									str+='<div class="row" style="height:30px;clear:both;margin-top:15px">';
									str+='<div class="col-xs-4"  >';
									str+='<label class="control-label" style="text-align:right;float:right;line-height:30px;width:100%">'+diagDescLabel+'</label>';
									str+='</div>';
									str+='<div class="col-xs-6"">';
									str+='<select  id="hICDDesc"  class="form-control select " placeholder="" ></select> ';
									str+='</div>';
									str+='</div>';
									str+='<div class="row" style="height:20px;clear:both;margin-top:10px">';
									str+='<div class="col-xs-10"  >';
									str+='<label style="text-align:right;float:right;width:100%;color:#ff0000;font-weight:normal">'+diagDescInput+'</label>';
									str+='</div>';
									str+='</div>';
									str+='<div class="row" style="height:30px;clear:both;margin-top:15px">';
									str+='<div class="col-xs-4"  >';
									str+='<label class="control-label" style="text-align:right;float:right;line-height:30px;width:100%">'+bjCodeLabel+'</label>';
									str+='</div>';
									str+='<div class="col-xs-6"">';
									str+='<input id="BJICDCode" type="text" class="form-control" placeholder="'+bjCodeInput+'" onblur="findBJDiagOrOperateDescByCode(\''+icdType+'\')">  ';
									str+='</div>';
									str+='</div>';
									str+='<div class="row" style="height:30px;clear:both;margin-top:15px">';
									str+='<div class="col-xs-4"  >';
									str+='<label class="control-label" style="text-align:right;float:right;line-height:30px;width:100%">'+bjCodeDescLabel+'</label>';
									str+='</div>';
									str+='<div class="col-xs-6"">';
									str+='<input id="BJICDDesc" type="text" class="form-control" placeholder="" >  ';
									str+='</div>';
									str+='</div>';
									str+='</div> </div>'
									dialog.find(".modal-body").append(str);//向弹出框添加
									var footStr = '';
									footStr+='<div style="text-align:right">';
									footStr+='<button id="operCancle" class="btn btn-primary" data-dismiss="modal">取消</button>';
									footStr+='<button id="operSave" class="btn btn-primary" data-dismiss="modal">保存</button>';
									footStr+='</div>';
									dialog.find(".modal-footer").append(footStr);
					
									/**
									 * 把更新的内容传入到后端
									 */
									dialog.find('#operSave').on('click',function(){
										var icdVersion = $("#"+tabId+" #icdVersion").val();
										var hICDCode = dialog.find('#hICDCode').val();
										var hICDDesc = dialog.find('#hICDDesc').val();
										var BJICDCode = dialog.find('#BJICDCode').val();
										var BJICDDesc = dialog.find('#BJICDDesc').val();
										if(!(hICDCode && hICDDesc  && BJICDCode && BJICDDesc)){
											drgUI.warning("数据不完整！");
											return ;
										} 
										$.ajax({
											url : contextPath + '/matchIcd/updateOneICDPlatform.dhc',
											data : {
												"icdType":icdType,
												"icdVersion":icdVersion,
												"hICDCode":hICDCode,
												"hICDDesc":hICDDesc,
												"bjICDCode":BJICDCode,
												"bjICDDesc":BJICDDesc
											},
											type : 'post',
											async : true,
											dataType : "json",// 这里的dataType就是返回回来的数据格式了html,xml,json
											cache : false,// 设置是否缓存，默认设置成为true，当需要每次刷新都需要执行数据库操作的话，需要设置成为false
											success : function(result){
												if(!result.success){
													drgUI.error(result.errorMessage) ;
								    			}else{
													drgUI.success("更新成功");
													if(ckd){
														loadTableData(1);
													}else{
														loadTableData(0);
													}
												}
											}
										});
									});
								}
						});
			});
	}
	//
});

/**
 * 获取加载数据
 * @param 
 * @returns
 */
function loadTableData(isOnlyMatch){
	$('#'+tabId+' #table-div').html('<table id="icdMatchResult-table" class="table table-striped" style="width:100%"></table>');
	var icdType=$("#"+tabId+" #icdTypeId").val();
	var icdVersion=$("#"+tabId+" #icdVersion").val();
	var param = {"icdType":icdType,"icdVersion":icdVersion,"isOnlyMatch": isOnlyMatch};
	$.post(contextPath+"/matchIcd/getICDMatchResultTablePlatform.dhc", param).done(function(result){
		if(result.success){
			var data = result.data;
			var columns=[];
			var paramsDataTables={lengthChange:true,scrollY:'500px',scrollX:true,paging:true,ordering:true,pageLength:50,order:[[ 2, "desc" ]]};
			if(isOnlyMatch=='1'){
				 columns = [{
	         	   "data": "ICDCODE",
	         	   "title":"本院编码描述"
	            },{
	         	   "data": "ICDDESC",
	         	   "title":"本院编码描述"
	            },{
	         	   "data": "caseCnt",
	         	   "title":"出院病例数",
	         	   "render":function(obj, type, full){
	         		 if (data.caseCnt != 0) {
							return "<a href='javascript:caseData(\""
									+ icdType + "\",\""+ full.ICDCODE+ "\",\""+ full.ICDDESC+ "\")'>"
									+ formatNumber(full.caseCnt)
									+ "</a>";
						}
	         		return formatNumber(full.caseCnt);
	         	  }
	            }];
			}else{
				  columns = [{
	         	   "data": "ICDCODE",
	         	   "title":"本院编码描述"
	            },{
	         	   "data": "ICDDESC",
	         	   "title":"本院编码描述"
	            },{
	         	   "data": "BJICDCODE",
	         	   "title":"北京版编码"
	            },{
	         	   "data": "BJICDDESC",
	         	   "title":"北京版描述"
	            }];
				  paramsDataTables={lengthChange:true,scrollY:'500px',scrollX:true,paging:true,ordering:true,pageLength:50};
			}

			$("#"+tabId+" #icdMatchResult-table").dataTableBasic(columns,data,paramsDataTables);
		}
		if(isOnlyMatch==1){
			$('#showUnvalidResult').iCheck('check');
		}else{
			$('#showUnvalidResult').iCheck('uncheck');
		}
	});
}

//病例明细跳转
function caseData(icdType,icdCode,icdDesc) {

	$("#modalcq .close").click();
	var pageId = icdType +icdCode+ "CaseList";

	var param = jQuery.extend(true, {}, paramTabPage[tabId]);
	param.icdType = icdType;
	param.icdCode = icdCode;
	param.icdDesc = icdDesc;
	var desc=""
	if(icdType=="D"){
		desc = "诊断未对照";
	}else {
		desc = "手术未对照";
	}

	openTab('/pages/icdMatch/result/icdMatchCase.jsp', desc + "|" + '病例明细', pageId, pageId,
			param);

}

/**
 * @void
 * @ Discription:根据诊断/手术编码获取描述
 */
function findDiagOrOperateDescByCode(icdType){
	var code=$('#hICDCode').val();
	if(!code) return;
	$('#hICDDesc').html();
	var str='<option value="none">请填写正确'+(icdType =='D' ? '诊断':'手术')+'编码</option>';
	$.post(contextPath + "/matchIcd/findDescByCode.dhc",{"type":icdType,"code":code}).done(function(result){
		if(result.success && result.data.length>0){
			str="";
			var data= result.data;
			for(var i in data){
				str +='<option value="'+data[i].NAME+'">'+data[i].NAME+'('+data[i].CNT+')</option>';
			}
			$('#hICDDesc').html(str);	
		}else{
			$('#hICDDesc').html(str);
		}	
	});
}
/**
 * @void
 * @ Discription:根据BJ诊断/手术编码获取描述
 */
function findBJDiagOrOperateDescByCode(icdType){
	var code=$('#BJICDCode').val();
	var icdVersion = $("#"+tabId+" #icdVersion").val();
	if(!code) return;
	$.post(contextPath + "/matchIcd/findBJDescByCode.dhc",{"type":icdType,"code":code,"icdVersion":icdVersion}).done(function(result){
		if(result.success && result.data.length>0){
			var data= result.data;
			$('#BJICDDesc').val(data[0].NAME);	
		}else{
			$('#BJICDDesc').attr("placeholder","请输入正确编码");
		}	
	});
}